﻿using AutoMapper;
using YDT_ProductService.Application.DTOs;
using YDT_ProductService.Application.Interfaces;
using YDT_ProductService.Domains.Entities;
using YDT_ProductService.Domains.Enums;
using YDT_ProductService.Domains.Interfaces;

namespace YDT_ProductService.Application.Services
{
    /// <summary>
    /// 商品应用服务实现 - 协调领域对象完成业务用例
    /// </summary>
    public class ProductService : IProductService
    {
        private readonly IProductRepository _productRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数 - 依赖注入
        /// </summary>
        public ProductService(IProductRepository productRepository, IMapper mapper)
        {
            _productRepository = productRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据ID获取商品
        /// </summary>
        public async Task<ProductDto?> GetProductByIdAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 根据商品编码获取商品
        /// </summary>
        public async Task<ProductDto?> GetProductByCodeAsync(string productCode)
        {
            var product = await _productRepository.GetByProductCodeAsync(productCode);
            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 获取所有商品
        /// </summary>
        public async Task<IEnumerable<ProductDto>> GetAllProductsAsync()
        {
            var products = await _productRepository.GetAllAsync();
            return _mapper.Map<IEnumerable<ProductDto>>(products);
        }

        /// <summary>
        /// 根据状态获取商品
        /// </summary>
        public async Task<IEnumerable<ProductDto>> GetProductsByStatusAsync(ProductStatus status)
        {
            var products = await _productRepository.GetByStatusAsync(status);
            return _mapper.Map<IEnumerable<ProductDto>>(products);
        }

        /// <summary>
        /// 分页查询商品
        /// </summary>
        public async Task<(IEnumerable<ProductDto> Products, int TotalCount)> GetPagedProductsAsync(ProductQueryDto query)
        {
            // 这里简化实现，实际项目中可能需要更复杂的查询逻辑
            var (products, totalCount) = await _productRepository.GetPagedAsync(query.PageIndex, query.PageSize);
            var productDtos = _mapper.Map<IEnumerable<ProductDto>>(products);
            return (productDtos, totalCount);
        }

        /// <summary>
        /// 创建商品
        /// </summary>
        public async Task<ProductDto> CreateProductAsync(CreateProductDto createProductDto)
        {
            // 检查商品编码是否已存在
            if (await _productRepository.ProductCodeExistsAsync(createProductDto.ProductCode))
            {
                throw new ArgumentException($"商品编码 '{createProductDto.ProductCode}' 已存在");
            }

            // 创建商品实体
            var product = new Product(
                createProductDto.Id,
                createProductDto.ProductCode,
                createProductDto.ProductTitle,
                createProductDto.ProductDescription,
                createProductDto.ProductPrice,
                createProductDto.ProductStock,
                createProductDto.ProductUrl,
                createProductDto.ProductVirtualprice,
                createProductDto.ProductSort
            );

            // 添加商品图片
            foreach (var imageDto in createProductDto.ProductImages)
            {
                product.AddProductImage(imageDto.ImageUrl, imageDto.ImageSort, imageDto.ImageStatus);
            }

            // 保存到数据库
            await _productRepository.AddAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 更新商品
        /// </summary>
        public async Task<ProductDto?> UpdateProductAsync(Guid id, UpdateProductDto updateProductDto)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            // 更新商品基本信息
            product.UpdateBasicInfo(
                updateProductDto.ProductTitle,
                updateProductDto.ProductDescription,
                updateProductDto.ProductPrice,
                updateProductDto.ProductVirtualprice,
                updateProductDto.ProductSort,
                updateProductDto.ProductUrl
            );

            // 保存到数据库
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        public async Task<bool> DeleteProductAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return false;

            await _productRepository.DeleteAsync(id);
            return true;
        }

        /// <summary>
        /// 更新商品库存
        /// </summary>
        public async Task<ProductDto?> UpdateProductStockAsync(Guid id, int newStock)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.UpdateStock(newStock);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 增加商品库存
        /// </summary>
        public async Task<ProductDto?> IncreaseProductStockAsync(Guid id, int quantity)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.IncreaseStock(quantity);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 减少商品库存
        /// </summary>
        public async Task<ProductDto?> DecreaseProductStockAsync(Guid id, int quantity)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.DecreaseStock(quantity);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 增加商品销量
        /// </summary>
        public async Task<ProductDto?> IncreaseProductSoldAsync(Guid id, int quantity)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.IncreaseSold(quantity);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 激活商品
        /// </summary>
        public async Task<ProductDto?> ActivateProductAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.Activate();
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 禁用商品
        /// </summary>
        public async Task<ProductDto?> DeactivateProductAsync(Guid id)
        {
            var product = await _productRepository.GetByIdAsync(id);
            if (product == null) return null;

            product.Deactivate();
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 添加商品图片
        /// </summary>
        public async Task<ProductDto?> AddProductImageAsync(Guid productId, CreateProductImageDto imageDto)
        {
            var product = await _productRepository.GetByIdAsync(productId);
            if (product == null) return null;

            product.AddProductImage(imageDto.ImageUrl, imageDto.ImageSort, imageDto.ImageStatus);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }

        /// <summary>
        /// 移除商品图片
        /// </summary>
        public async Task<ProductDto?> RemoveProductImageAsync(Guid productId, Guid imageId)
        {
            var product = await _productRepository.GetByIdAsync(productId);
            if (product == null) return null;

            product.RemoveProductImage(imageId);
            await _productRepository.UpdateAsync(product);

            return _mapper.Map<ProductDto>(product);
        }
    }
}
